import 'package:flutter/cupertino.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

class DBHelper {
  static String dbName = "db.db";
  static Database? database;

  static  openDb() {
    if (database == null) {
      _init();
    }
  }

  static insertDb( int spid,String name, String taxon) async {
    await database?.transaction((txn) async {
      int id1 = await txn.rawInsert('INSERT INTO favor_tab(spid, name,taxon) VALUES(?, ?, ?)', [spid,name,taxon]);
    });
    debugPrint("插入成功");
  }

  static deleteBySpid(int spid) async {
    database?.transaction((txn) async{
      await txn?.rawDelete(
      'DELETE FROM favor_tab WHERE spid = ?',
      [spid],
      );
    });
    debugPrint("删除成功");
  }


  static listAllFavor() async{
    List<Map<String, Object?>>? records=  await database?.rawQuery('SELECT * FROM favor_tab');
    return records;
  }

   static Future<bool> isExistFavor(int spid) async {
    final result = await database?.rawQuery(
      'SELECT COUNT(*) FROM favor_tab WHERE spid = ?',
      [spid],
    );
    int count = Sqflite.firstIntValue(result!) ?? 0;
    return count > 0;
  }

  static _init() async {
    var databasesPath = await getDatabasesPath();
    String path = join(databasesPath, dbName);
    database = await openDatabase(
      path,
      version: 1,
      onUpgrade: (Database db, int oldVersion, int newVersion) {

      },
      onCreate: (Database db, int version) async {
        await db.execute('''
  CREATE TABLE IF NOT EXISTS favor_tab (
    spid INTEGER PRIMARY KEY,
    name TEXT,
    taxon TEXT
  );
''');
      },
    );
    debugPrint("数据库初始化完毕");
  }

  static closedb(){
    database?.close();
  }
}
